<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AgentController
 *
 * @author LeVinh
 */
include_once APPLICATION_PATH."/models/Agent.php";
include_once APPLICATION_PATH."/models/Product.php";
include_once APPLICATION_PATH."/models/Order_Detail.php";
include_once APPLICATION_PATH."/models/User.php";
include_once APPLICATION_PATH."/models/Province.php";
include_once APPLICATION_PATH."/models/District.php";
include_once APPLICATION_PATH."/models/Area_Province_Category.php";
class Admin_AgentController extends Zend_Controller_Action {
    public function init() {
        $bootstrap = $this->getInvokeArg("bootstrap");
        $this->aConfig = $bootstrap->getOptions();
        $this->view->aConfig = $this->aConfig;
        $this->model = new Model_Agent();
        $this->modelMapper = new Model_AgentMapper();
        $this->Productmodel = new Model_Product();
        $this->ProductmodelMapper = new Model_ProductMapper();
        $this->OrderDetailmodel = new Model_Order_Detail();
        $this->OrderDetailmodelMapper = new Model_Order_DetailMapper();
        $this->UsermodelMapper = new Model_UserMapper();
        $this->Usermodel = new Model_User();
        $this->Provincemodel= new Model_Province();
        $this->ProvincemodelMapper= new Model_ProvinceMapper();
        $this->Districtmodel=new Model_District();
        $this->DistrictmodelMapper= new Model_DistrictMapper();
        $this->AreaAgentmodel= new Model_Area_Province_Category();
        $this->AreaAgentmodelMapper= new Model_Area_Province_CategoryMapper();
    }
    public function indexAction() {}
    public function listAction() {}
    public function liststoreAction(){}
    public function serviceAction(){       
        $this->_helper->layout->disableLayout();
        $menber=null;

        foreach ($this->modelMapper->getAgent(1) as $items){
            if($items['province_name']==''){
                $province_name="";
            } else{
                $province_name=$items['province_name'];
            }
            if($items['district_name']==''){
                $district_name="";
            } else {
                $district_name=$items['district_name'];
            }
            $menber[]=array(
                'id'=>$items['agent_id'],
                'agent_name'=>$items['agent_name'].'||'.$items['agent_id'].'||'.$items['agent_status'].'||',               
                'user_id'=>$items['user_id'],
                'charges'=>$items['charges'],
                'district_name'=>$district_name,
                'province_name'=>$province_name
            );
        }
        echo json_encode($menber);
        exit();
    }
    public function service2Action(){       
        $this->_helper->layout->disableLayout();
        $menber=null;

        foreach ($this->modelMapper->getAgent(2) as $items){
            if($items['province_name']==''){
                $province_name="";
            } else{
                $province_name=$items['province_name'];
            }
            if($items['district_name']==''){
                $district_name="";
            } else {
                $district_name=$items['district_name'];
            }
            $menber[]=array(
                'id'=>$items['agent_id'],
                'agent_name'=>$items['agent_name'].'||'.$items['agent_id'].'||'.$items['agent_status'].'||',               
                'user_id'=>$items['user_id'],
                'charges'=>$items['charges'],
                'district_name'=>$district_name,
                'province_name'=>$province_name
            );
        }
        echo json_encode($menber);
        exit();
    }
    public function storeAction() {}
    public function addAction()
    {
        $redirect = $this->_getParam("redirect",1); 
        if ($this->getRequest()->isPost()) {               
            
            if (isset($_POST["id"])) {
                $this->model->setId($_POST["id"]);
            }
            if (isset($_POST["name"])) {
                $this->model->setName($_POST["name"]);
            }            
            if (isset($_POST["address"])) {
                $this->model->setAddress($_POST["address"]);
            }
            if (isset($_POST["province_id"])) {
                $this->model->setProvince_Id($_POST["province_id"]);
            }
            if (isset($_POST["district_id"])) {
                $this->model->setDistrict_Id($_POST["district_id"]);
            }
            if (isset($_POST["representavie"])) {
                $this->model->setRepresentavie($_POST["representavie"]);
            }
            if (isset($_POST["phone"])) {
                $this->model->setPhone($_POST["phone"]);
            }
            
            $this->model->setCharges(0);
            $this->model->setCharges_Sell(0);
            if (isset($_POST["agent_cat_id"])) {
                $this->model->setAgent_Cat_Id($_POST["agent_cat_id"]);
                $redirect = $_POST["agent_cat_id"];
            }
            if (isset($_POST["area_id"])) {
                $this->model->setArea_Id($_POST["area_id"]);
            }
            if (isset($_POST["user_id"])) {
                $this->model->setUser_Id($_POST["user_id"]);
            }
            if (isset($_POST["order"])) {
                $this->model->setOrder($_POST["order"]);
            }            
            if (isset($_POST["status"])) {
                $status = 1;
            } else {
                $status = 0;
            }            
            $this->model->setStatus($status);
            if(isset($_POST["legal_capital"])){
                $this->model->setLegal_Capital($_POST["legal_capital"]);
            }
            if(isset($_POST["experience"])){
                $this->model->setExperience($_POST["experience"]);
            }
            if(isset($_POST["ability_archive"])){
                $this->model->setAbility_Archive($_POST["ability_archive"]);
            }
            if(isset($_POST["ability_transport"])){
                $this->model->setAbility_Transport($_POST["ability_transport"]);
            }
            if(isset($_POST["person"])){
                $this->model->setPerson($_POST["person"]);
            }
            if(isset($_POST["agent_status"]))
            {
                $this->model->setAgent_Status($_POST["agent_status"]);
            }
            if(isset($_POST["tax_code"]))
            {
                $this->model->setTax_Code($_POST["tax_code"]);
            }
            if(isset($_POST["identity_card"])){
                $this->model->setIdentity_Card($_POST["identity_card"]);
            }
            if(strlen($_POST["birthday"])>0){
                $this->model->setBirthday(GlobalLib::toMysqlDateString($_POST["birthday"]));
            }
            $this->model->setCreated(date("Y/m/d H:i:s"));
            $this->model->setCreated_By(GlobalLib::getLoginId());
            $this->model->setModified(date("Y/m/d H:i:s"));
            $this->model->setModified_By(GlobalLib::getLoginId());
            $this->modelMapper->save($this->model);
            //Quyet dinh redirect toi DL hoac Cua Hang
            $redirectUrl = $this->aConfig["site"]["url"] . "/admin/agent/index";
            if($redirect>1) $redirectUrl = $this->aConfig["site"]["url"] . "/admin/agent/store";
            $this->_redirect($redirectUrl);
        }
        $this->view->redirect = $redirect;
        $this->view->item = $this->model;
        $province_id= $this->model->getProvince_Id();
        if(empty($province_id)){
            $province_id=0;
        }
        if(empty($area_id)){
            $area_id=0;
        }
        $this->view->areaHTML= GlobalLib::getComboByArea('area_id', 'area', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'admin/province/getprovince\',$(\'#area_id\').val(),\'province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->provinceHTML= GlobalLib::getComboByProvince('province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= '.$area_id.')', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'admin/district/getdistrict\',$(\'#province_id\').val(),\'district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->districtHTML=GlobalLib::getComboByDistrict('district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id=' . $province_id);   
    }    
    
    public function editAction(){
        $id = $this->_getParam("id","");        
        $this->view->itemm=$id;
        //$redirectUrl=$this->aConfig["site"]["url"]."admin/agent/index";
        if(empty($id)){
            $this->_redirect($redirectUrl);
        }
        $this->modelMapper->find($id,$this->model);
        $getId=$this->model->getId();
        if(empty($getId)){
            $this->_redirect($redirectUrl);
        }
        if($this->getRequest()->isPost()){
          if (isset($_POST["id"])) {
                $this->model->setId($_POST["id"]);
            }
            if (isset($_POST["name"])) {
                $this->model->setName($_POST["name"]);
            }            
            if (isset($_POST["address"])) {
                $this->model->setAddress($_POST["address"]);
            }
            if (isset($_POST["province_id"])) {
                $this->model->setProvince_Id($_POST["province_id"]);
            }
            if (isset($_POST["district_id"])) {
                $this->model->setDistrict_Id($_POST["district_id"]);
            }
            if (isset($_POST["representavie"])) {
                $this->model->setRepresentavie($_POST["representavie"]);
            }
            if (isset($_POST["phone"])) {
                $this->model->setPhone($_POST["phone"]);
            }
            if (isset($_POST["charges"])) {
                $this->model->setCharges($this->model->getCharges());
            }
            if (isset($_POST["agent_cat_id"])) {
                $this->model->setAgent_Cat_Id($_POST["agent_cat_id"]);
                $redirect = $_POST["agent_cat_id"];
            }
            if (isset($_POST["area_id"])) {
                $this->model->setArea_Id($_POST["area_id"]);
            }
            if (isset($_POST["user_id"])) {
                $this->model->setUser_Id($_POST["user_id"]);
            }
            if (isset($_POST["order"])) {
                $this->model->setOrder($_POST["order"]);
            }            
            if (isset($_POST["status"])) {
                $status = 1;
            } else {
                $status = 0;
            }  
            if(isset($_POST["legal_capital"])){
                $this->model->setLegal_Capital($_POST["legal_capital"]);
            }
            if(isset($_POST["experience"])){
                $this->model->setExperience($_POST["experience"]);
            }
            if(isset($_POST["ability_archive"])){
                $this->model->setAbility_Archive($_POST["ability_archive"]);
            }
            if(isset($_POST["ability_transport"])){
                $this->model->setAbility_Transport($_POST["ability_transport"]);
            }
            if(isset($_POST["person"])){
                $this->model->setPerson($_POST["person"]);
            }
            if(isset($_POST["agent_status"]))
            {
                $this->model->setAgent_Status($_POST["agent_status"]);
            }
            if(isset($_POST["tax_code"]))
            {
                $this->model->setTax_Code($_POST["tax_code"]);
            }
            if(isset($_POST["identity_card"])){
                $this->model->setIdentity_Card($_POST["identity_card"]);
            }
            if(strlen($_POST["birthday"])>0){
                $this->model->setBirthday(GlobalLib::toMysqlDateString($_POST["birthday"]));
            }
            if(isset($_POST["ability_sell"])){
                $this->model->setAbility_Sell($_POST["ability_sell"]);
            }
            $this->model->setStatus($status);
            $this->model->setCreated(date("Y/m/d H:i:s"));
            $this->model->setCreated_By(GlobalLib::getLoginId());
            $this->model->setModified(date("Y/m/d H:i:s"));
            $this->model->setModified_By(GlobalLib::getLoginId());
            $this->modelMapper->save($this->model);
            //Quyet dinh redirect toi DL hoac Cua Hang
            $redirectUrl = $this->aConfig["site"]["url"] . "/admin/agent/index";
            if($redirect>1) $redirectUrl = $this->aConfig["site"]["url"] . "/admin/agent/store";
            $this->_redirect($redirectUrl);          
        }
        $this->view->item=$this->model;
        $province_id= $this->model->getProvince_Id();
        if(empty($province_id)){
            $province_id=0;
        }
        if(empty($area_id)){
            $area_id=0;
        }
        $this->view->areaHTML= GlobalLib::getComboByArea('area_id', 'area', 'id', 'name', $this->model->getArea_Id(), false, 'form-control', '', '', '', 'onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'admin/province/getprovince\',$(\'#area_id\').val(),\'province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->provinceHTML= GlobalLib::getComboByProvince('province_id', 'province', 'id', 'name', $this->model->getProvince_Id(), false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= '.$this->model->getArea_Id().')', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'admin/district/getdistrict\',$(\'#province_id\').val(),\'district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->districtHTML=GlobalLib::getComboByDistrict('district_id', 'district', 'id', 'name', $this->model->getDistrict_Id(), false, 'form-control', '', 'where province_id=' . $province_id);   
    }
    public function deleteAction(){
        $id= $this->_getParam("id","");
        $redirectUrl=$this->aConfig["site"]["url"]."admin/agent/index";                       
        $this->modelMapper->delete($id);
        $this->_redirect($redirectUrl);        
    }    
    public function getagentAction(){
        $this->_helper->layout()->disableLayout();
                $agentHTML = '<select name="agent_id" style="width: 386px;"><option value=""></option></select>';
                if ($this->_request->isPost()) {
                    $area_id = $this->_getParam("area_id", "");
                    if (is_numeric($area_id)) {
                        $agentHTML = GlobalLib::getCombo('agent_id', 'agent', 'id', 'name', 0, false, 'where area_id in (select id from area where id=' . $area_id.')');
                    }
                }
                echo '[{"html":\'' . $agentHTML . '\'}]';
                exit;
    }
    public function getagentdistrictAction(){
        $this->_helper->layout()->disableLayout();
                $agentHTML = '<select name="agent_id" style="width: 386px;"><option value=""></option></select>';
                if ($this->_request->isPost()) {
                    $district = $this->_getParam("district_id", "");
                    if (is_numeric($district)) {
                        $agentHTML = GlobalLib::getCombo('agent_id', 'agent', 'id', 'name', 0, false, 'where district_id =' . $district.'');
                    }
                }
                echo '[{"html":\'' . $agentHTML . '\'}]';
                exit;
    }
    
    public function adduserAction() {
        $username = $this->getParam("username","");
        $password = $this->getParam("password","");
        $firstname = $this->getParam("firstname","");
        $lastname = $this->getParam("lastname","");
        $phone = $this->getParam("phone","");
        
        $order = $this->getParam("order","");
        $status = $this->getParam("status","");
        $agent_id = $this->getParam("agent_id","0");
        $this->Usermodel->setUsername($username);
        $this->Usermodel->setPassword(md5($password));
        $this->Usermodel->setFirst_Name($firstname);
        $this->Usermodel->setLast_Name($lastname);
        $this->Usermodel->setPhone($phone);
       
        $this->Usermodel->setOrder($order);
        $this->Usermodel->setStatus($status);
        $this->Usermodel->setCreated(date("Y/m/d H:i:s"));
        $this->Usermodel->setCreated_By(GlobalLib::getLoginId());
        $this->Usermodel->setModified(date("Y/m/d H:i:s"));
        $this->Usermodel->setModified_By(GlobalLib::getLoginId());
        $this->UsermodelMapper->save($this->Usermodel);    
        $this->modelMapper->find($agent_id,$this->model);
        $this->model->setUser_Id($this->UsermodelMapper->getlastid());
        $this->modelMapper->save($this->model);        
        echo $this->UsermodelMapper->getlastid();
        exit();
    }
    public function exportfileAction(){
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename=' . $filename);
        header('Cache-Control: max-age=0');
    }
    public function importagentAction(){
        $this->_helper->layout->disableLayout();
        if ($this->_request->isPost()) {
            $mimes = array(
                '.xls',
                '.xlsx'
            );
            if (isset($_FILES['my_file'])) {
                $fileName = $_FILES['my_file']['name'];
                $fileTmp=$_FILES['my_file']['tmp_name'];
                $fileType = $_FILES['my_file']['type'];
                $fileError = $_FILES['my_file']['error'];
                $file_ext = strtolower(substr($fileName,strrpos($fileName,".")));
                $fileStatus = array(
                    'status' => 0,
                    'message' => ''
                );
                if(!in_array($file_ext, $mimes)){
                    $fileStatus['message'] = 'Không cho phép định dạng này';
                } else {
                    $total = $this->import_users_from_xls($fileTmp);
                    if ($total !== false) {
                        $fileStatus['status'] = 1;
                        $fileStatus['message'] = $total . ' Đại lý/Cửa Hàng đã được thêm thành công.';
                    } else {
                        $fileStatus['message'] = 'Not able to process this file.';
                    }
                }
                echo json_encode($fileStatus);
                exit();
        }
    }
    }

    function import_users_from_xls($path_tmp_name) {
        ini_set('memory_limit', '128M');
        ini_set('max_execution_time', 0);
        $total = 0;
        $total_user = 0;
        $inputFileType = PHPExcel_IOFactory::identify($path_tmp_name);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objReader->setReadDataOnly(true);
        /**  Load $inputFileName to a PHPExcel Object  * */
        $objPHPExcel = $objReader->load($path_tmp_name);
        $test = array();
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
            $highrow = $worksheet->getHighestRow();
            $highcolumn = $worksheet->getHighestColumn();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highcolumn);
            for ($row = 5; $row <= $highrow; $row++) {
                $agent_name = $worksheet->getCellByColumnAndRow(1, $row);
                $agent_cat = $worksheet->getCellByColumnAndRow(2, $row);
                $agent_address = $worksheet->getCellByColumnAndRow(3, $row);
                $agent_district = $worksheet->getCellByColumnAndRow(4, $row);
                $agent_province = $worksheet->getCellByColumnAndRow(5, $row);
                $agent_phone = $worksheet->getCellByColumnAndRow(6, $row);
                $agent_repense = $worksheet->getCellByColumnAndRow(7, $row);
                $agent_birthday=$worksheet->getCellByColumnAndRow(8,$row);
                $agent_username = $worksheet->getCellByColumnAndRow(9, $row);
                $agent_password = $worksheet->getCellByColumnAndRow(10, $row);
                $user_id="";
                $birthday_import=null;
                if(strlen(trim($agent_birthday->getValue()))>4){
                    $birthdayagent = PHPExcel_Style_NumberFormat::toFormattedString($agent_birthday->getValue(), 'YYYY-MM-DD');
                    $birthdayagent = str_replace("/", "-", $birthdayagent);
                    $check= explode("-", $birthdayagent);
                    if($check[0]>1000)
                    {
                        $birthday_import=$birthdayagent;                
                    }  else {
                        $t_day = $check[0]; if (strlen($t_day)==1) $t_day = "0".$t_day;
                        $t_month = $check[1]; if (strlen($t_month)==1) $t_month = "0".$t_month;
                        $t_year = $check[2];
                        $_str=$t_year."-".$t_month."-".$t_day;
                        $birthday_import=date("Y-m-d", strtotime($_str)); 
                    }
                }
                if(strlen(trim($agent_birthday->getValue()))==4){ 
                    $birthday_import=date("Y-m-d", strtotime(trim($agent_birthday->getValue())."-01-01"));
                }
                
                //array_push($test, PHPExcel_Style_NumberFormat::toFormattedString($agent_birthday->getValue(), 'YYYY-MM-DD'));
                if($agent_username->getValue()!="" && $agent_password->getValue()!=""){
                    $this->Usermodel->setUserName(trim($agent_username->getValue()));
                    $this->Usermodel->setPassword(md5($agent_password->getValue()));
                    $this->Usermodel->setPhone($agent_phone->getValue());
                    $this->Usermodel->setLast_Name($agent_name->getValue());
                    if(isset($birthday_import)) $this->Usermodel->setBirthday($birthday_import);
                     else $this->Usermodel->setBirthday(null);
//                    $birthdayuser = PHPExcel_Style_NumberFormat::toFormattedString($agent_birthday->getValue(), 'YYYY-MM-DD');
//                    $birthdayuser = str_replace("/", "-", $birthdayuser);
                    
//                    $check = explode("-", $birthdayuser);
//                    if ($check[0] > 1000) {
//                        $this->Usermodel->setBirthday($birthdayuser);
//                    } else {
//                        $t_day = $check[0];
//                        if (strlen($t_day) == 1)
//                            $t_day = "0" . $t_day;
//                        $t_month = $check[1];
//                        if (strlen($t_month) == 1)
//                            $t_month = "0" . $t_month;
//                        $t_year = $check[2];
//
//                        $_str = $t_year . "-" . $t_month . "-" . $t_day;
//                        $this->Usermodel->setBirthday(date("Y-m-d", strtotime($_str)));
//                    }
                    $this->Usermodel->setCreated(date("Y/m/d H:i:s"));
                    $this->Usermodel->setCreated_By(GlobalLib::getLoginId());
                    $this->Usermodel->setModified(date("Y/m/d H:i:s"));
                    $this->Usermodel->setModified_By(GlobalLib::getLoginId());
                    $this->Usermodel->setStatus(1);
                    $this->UsermodelMapper->save($this->Usermodel);
                    $user_id = $this->UsermodelMapper->getlastid();
                    $total_user++;                    
                }
                $province_code = $this->ProvincemodelMapper->findidbycode($agent_province->getValue());
                if($province_code==NULL){
                    $province_id="";
                } else {
                    $province_id=$province_code;
                }
                $district_code=$this->DistrictmodelMapper->findidbycode($agent_district->getValue());
                if($district_code==NULL){
                    $district_id="";
                } else {
                    $district_id=$district_code;
                }
                $area_code = $this->AreaAgentmodelMapper->findareaidbyprovinceid($province_id);
                if($area_code==NULL){
                    $area_id="";
                } else {
                    $area_id=$area_code;
                }
                $this->model->setName($agent_name->getValue());
                $this->model->setAddress($agent_address->getValue());
                $this->model->setProvince_Id($province_id);
                $this->model->setDistrict_Id($district_id);
                $this->model->setRepresentavie($agent_repense->getValue());
                $this->model->setPhone($agent_phone->getValue());
                $this->model->setAgent_Cat_Id($agent_cat->getValue());
                $this->model->setArea_Id($area_id);
                if(isset($birthday_import)) $this->model->setBirthday($birthday_import);
                else $this->model->setBirthday(null);
//                $birthdayagent = PHPExcel_Style_NumberFormat::toFormattedString($agent_birthday->getValue(), 'YYYY-MM-DD');
//                $birthdayagent = str_replace("/", "-", $birthdayagent);
//                $check= explode("-", $birthdayagent);
////                if($check[0]>1000)
////                {
////                    $this->model->setBirthday($birthdayagent);                
////                }  else {
////                    $t_day = $check[0]; if (strlen($t_day)==1) $t_day = "0".$t_day;
////                    $t_month = $check[1]; if (strlen($t_month)==1) $t_month = "0".$t_month;
////                    $t_year = $check[2];
////                    $_str=$t_year."-".$t_month."-".$t_day;
////                    $this->model->setBirthday(date("Y-m-d", strtotime($_str))); 
////                }
                $this->model->setCreated(date("Y/m/d H:i:s"));
                $this->model->setCreated_by(GlobalLib::getLoginId());
                $this->model->setModified(date("Y/m/d H:i:s"));
                $this->model->setModified_By(GlobalLib::getLoginId());
                $this->model->setStatus(1);
                $this->model->setCharges(0);
                $this->model->setUser_Id($user_id);
                $this->model->setAgent_Status(2);
                $this->modelMapper->save($this->model);
                $total++;
            }
            //var_dump($test);exit();
        }
        return $total."-".$total_user;
    }
    
    public function checkagentnameAction(){
        $this->_helper->layout->disableLayout();
          if($this->_request->isPost()){
            $agent_name=$this->_getParam("agent_name","");
            $id=$this->modelMapper->checkAgentName($agent_name);
            if($id !=0){
                 $menber[]=array(
                     'code'=>1,
                     'message'=>''
                         );  
             } else {
                  $menber[]=array(
                     'code'=>0,
                     'message'=>''
                         );  
             }
             echo json_encode($menber);
             exit();
        }
    }
}
